package com.manager.seat.controller;

import com.manager.seat.model.TbSysUser;
import com.manager.seat.service.TbSysUserService;
import com.manager.seat.util.JsonResult;
import com.manager.seat.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName IoginController
 * @Description TODO
 * @date 2022/10/29 11:03
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/user/manager")
@Slf4j
public class LoginController {
    @Autowired
    TbSysUserService tbSysUserService;


    @GetMapping("/login")
    public JsonResult<TbSysUser> login(
            @RequestParam("userId") String userId,
            @RequestParam("password") String password,
            Model model,
            HttpServletRequest request,
            HttpServletResponse response) {
        TbSysUser user = tbSysUserService.getOne(userId);
        if (user != null && password.equals(user.getPassword())) {
            HttpSession session = request.getSession();
            model.addAttribute("msg", "登录成功！ 欢迎你！" + user.getUserName());
            session.setAttribute("userId", userId);
            session.setAttribute("userName", user.getUserName());
            // 创建一个 cookie对象
            Cookie cookie = new Cookie("userId", userId);
            //将cookie对象加入response响应
            response.addCookie(cookie);

        } else {
            model.addAttribute("msg", "登录失败！用户名或密码错误！");
            throw new RuntimeException("登陆失败！");
        }
        return new JsonResult<>(user);
    }

    @PostMapping("/register")
    public JsonResult<TbSysUser> register(@RequestBody TbSysUser param) {
        Assert.hasLength(param.getUserId(), "用户名或者学号不能为空");
        Assert.hasLength(param.getPassword(), "密码不能为空");
        TbSysUser user = tbSysUserService.getOne(param.getUserId());
        if (user != null) {
            throw new RuntimeException("已经有同样的userId注册！");
        }
        tbSysUserService.add(param);
        return new JsonResult<>(param);
    }




    @GetMapping("/logout")
    public JsonResult<String> logout(HttpSession session) {
        session.removeAttribute("userId");
        session.removeAttribute("userName");
        return new JsonResult("退出登陆成功！");
    }


    @GetMapping("/logging")
    public String logging() {
        //欢迎页面
        return "logging";
    }


}
